import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import multipleTaskForm from "../multipleTaskForm.vue";
import taskForm from "../taskForm.vue";
import { message } from "@/utils/message";
import { ElMessageBox, ElLoading } from 'element-plus'
import dayjs from 'dayjs';
import InvDetails from "@/views/task/invoicingDetail.vue";
import {
  projectListApi,
  projectStoreApi,
  projectUpdateApi,
  projectDeleteApi,
  projectShowApi,
  projectSelectApi,
  typeSelect
} from "@/api/projectApi";

import { taskBulkStoreApi, taskShowApi, taskUpdateApi } from "@/api/taskApi";
import { userSelectApi } from "@/api/user";
import { baseOaApi } from "@/api/utils";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 100,
    projectNo: "",
    projectName: "",
    listType: "createByMe",
    projectType: null,
    taskType: null,
    projectTypeOptions: [
      {id:1,name: '生产'},
      {id:2,name: '生产实施'},
      {id:3,name: '集成(有生产)'},
      {id:4,name: '集成(无生产)'},
      {id:5,name: '外包'},
      {id:6,name: '贸易'},
    ],
    taskTypeOptions: [],
    taskTypeOptionsCopy: [],
    status: null,
    timeType: null,
    rangeDate: null,
    electControl: null,
    consignType: null,
    isDelive: null,
    receiptFull: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 100,
    currentPage: 1,
    background: true,
    pageSizes: [10,20,50,100]
  });

  const columns: TableColumnList = [
    { type: "expand", slot: "expand", width: 36,fixed: "left",},
    {
      label: "项目名称",
      prop: "projectName",
      width: 200,
      fixed: "left",
    },
    {
      label: "项目编号",
      prop: "projectNo",
      minWidth: 130,
      sortable: true,
      // fixed: "left",
    },
    {
      label: "任务阶段",
      prop: "taskTypeName",
      minWidth: 120,
      slot: 'taskTypeName'
    },
    // {
    //   label: "子执行阶段",
    //   prop: "childTaskTypeName",
    //   minWidth: 110,
    //   formatter:(row: any)=> {
    //     return row.childTaskTypeName || '--'
    //   },
    // },
    {
      label: "剩余时间(天)",
      prop: "surplusDate",
      slot: "surplusDate",
      minWidth: 110
    },
    {
      label: "任务总数",
      prop: "taskCount",
      minWidth: 90
    },
    {
      label: "交付状态",
      prop: "isDelive",
      slot: "isDelive",
      minWidth: 90,
    },

    {
      label: "项目类型",
      prop: "projectType",
      slot: "projectType",
      minWidth: 100
    },
    {
      label: "货款类型",
      prop: "consignType",
      formatter:(row: any)=> {
        return row.consignType === 1? '发货款' : '到货款';
      },
      minWidth: 90
    },
    {
      label: "是否电控",
      prop: "electControl",
      formatter:(row: any)=> {
        return row.electControl === 1? '是' : '否';
      },
      minWidth: 90
    },
    {
      label: "实收款(%)",
      prop: "realReceiptRatio",
      minWidth: 90,
      formatter:(row: any)=> {
        return row.realReceiptRatio >= 100?100:row.realReceiptRatio
      },
    },
    {
      label: "预收款(%)",
      prop: "receiptRatio",
      minWidth: 90,
      formatter:(row: any)=> {
        return row.receiptRatio >= 100?100:row.receiptRatio
      },
    },
    {
      label: "状态",
      prop: "statusName",
      slot: "statusName",
      minWidth: 90
    },
    {
      label: "合同日期",
      prop: "startDate",
      formatter:(row: any)=> {
        return row.startDate + '至'+ row.endDate
      },
      minWidth: 190
    },
    {
      label: "计划日期",
      prop: "planStartDate",
      formatter:(row: any)=> {
        return row.planStartDate + '至'+ row.planEndDate
      },
      minWidth: 190
    },
    // {
    //   label: "合同附件",
    //   prop: "attachment",
    //   slot: "attachment",
    //   minWidth: 90
    // },
    // {
    //   label: "合同清单",
    //   prop: "contractList",
    //   slot: "contractList",
    //   minWidth: 90
    // },
    // {
    //   label: "技术协议",
    //   prop: "technicalProtocol",
    //   slot: "technicalProtocol",
    //   minWidth: 90
    // },

    // {
    //   label: "工作日(天)",
    //   prop: "effectDay",
    //   minWidth: 90
    // },
    // {
    //   label: "负责人",
    //   prop: "principalUser.name",
    //   minWidth: 100
    // },
    // {
    //   label: "创建人",
    //   prop: "createUser.name",
    //   minWidth: 100
    // },
    {
      label: "收款标识",
      prop: "receiptFull",
      slot: "receiptFull",
      minWidth: 110,
    },
    // {
    //   label: "描述",
    //   prop: "description",
    //   minWidth: 70,
    //   slot: 'description'
    // },
    // {
    //   label: "预算是否待定",
    //   prop: "budgetIsPend",
    //   formatter:(row: any)=> {
    //     return row.budgetIsPend === 1?'非待定':'待定'
    //   },
    //   minWidth: 120
    // },

    // {
    //   label: "访问控制",
    //   prop: "isPrivate",
    //   formatter:(row: any)=> {
    //     return row.isPrivate === 1?'公开':'私有'
    //   },
    //   minWidth: 80
    // },
    // {
      // label: "是否创建任务",
      // prop: "createTask",
      // formatter:(row: any)=> {
      //   return row.parent?.name
      // },
      // minWidth: 100
    // },
    // {
    //   label: "创建时间",
    //   prop: "createdAt",
    //   minWidth: 160
    // },
    // {
    //   label: "更新时间",
    //   prop: "updatedAt",
    //   minWidth: 160
    // },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 170
    }
  ];
  const expandColumns: TableColumnList = [
    // { type: "expand", slot: "expand", width: 10, fixed: "left",},
    {
      label: "任务阶段",
      prop: "taskTypeName",
      width: 170,
      fixed: "left",
    },
    {
      label: "状态",
      prop: "status",
      slot: "status",
      minWidth: 90
    },
    {
      label: "计划日期",
      prop: "planStartDate",
      formatter:(row: any)=> {
        return (row.planStartDate ?? '--') + '至'+ (row.planEndDate ?? '--')
      },
      minWidth: 280
    },
    {
      label: "实际日期",
      prop: "planStartDate",
      formatter:(row: any)=> {
        return (row.realStartDate ?? '--') + '至'+ (row.realEndDate ?? '--')
      },
      minWidth: 280
    },
    {
      label: "完成比例(%)",
      prop: "completeRate",
      minWidth: 110,
      formatter:(row: any)=> {
        let str: number = 0;
        if(row.completeRate) {
          str = row.completeRate*1
        }
        return str
      },
    },
    {
      label: "收款比例(%)",
      prop: "receiptRatio",
      minWidth: 110,
      formatter:(row: any)=> {
        let str: any = '--';
        if(row.taskType === 1020000 || row.taskType === 1070000 || row.taskType === 1090000 || row.taskType === 1120000 || row.taskType === 1130000) {
          str = row.receiptRatio
        }
        return str
      },
    },
    {
      label: "预计小时",
      prop: "expectHour",
      minWidth: 90,
      formatter:(row: any)=> {
        return row.expectHour || '--'
      },
    },
    // {
    //   label: "优先级",
    //   prop: "priority",
    //   minWidth: 90,
    //   formatter:(row: any)=> {
    //     return row.priority || '--'
    //   },
    // },
    // {
    //   label: "是否多人",
    //   prop: "hasMultiUser",
    //   minWidth: 90,
    //   formatter:(row: any)=> {
    //     return row.hasMultiUser === 0?'单人':'多人'
    //   },
    // },
    {
      label: "指派给用户",
      prop: "assigneds",
      minWidth: 120,
      slot: "assigneds"
    },
    {
      label: "抄送给用户",
      prop: "assignedExtraTo",
      minWidth: 120,
      slot: "assignedExtraTo"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 80
    }
  ]
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    onSearch();
  }

  async function onSearch() {

    let params = {
      page: form.page,
      perPage: form.perPage,
      listType: form.listType,
      projectName: form.projectName,
      projectNo: form.projectNo,
      projectType: form.projectType,
      taskType: form.taskType?form.taskType[form.taskType.length-1]:null,
      status: form.status,
      timeType: form.timeType,
      startTime: form.rangeDate ? form.rangeDate[0] : null,
      endTime: form.rangeDate ? form.rangeDate[1] : null,
      electControl: form.electControl,
      consignType: form.consignType,
      isDelive: form.isDelive,
      receiptFull: form.receiptFull,
    }
    if(form.rangeDate) {
      if(!form.timeType) {
        message('请选择时间类型', {
          type: "warning"
        });
        return
      }
    }
    if(form.projectName && form.projectName.length >0) {
      if(form.projectName.length < 4) {
        message(`项目名称必须在 4 到 100 个字符之间`, {
          type: "error"
        });
        return
      }
    }
    if(form.projectNo && form.projectNo.length >0) {
      if(form.projectNo.length < 8) {
        message(`项目编码必须在 8 到 30 个字符之间`, {
          type: "error"
        });
        return
      }
    }
    loading.value = true;
    const res: any = await projectListApi(toRaw(params));
    dataList.value = res?.result.list;
    // if(dataList.value && dataList.value.length > 0) {
    //   for (let item of dataList.value) {
    //     for (let row of item.taskList) {
    //       row.mechanicalList = [];
    //       row.electricalList = [];
    //       for (let child of row.childrens) {
    //         if(child) {
    //           if(child.taskType === 1030101 || child.taskType === 1030102 || child.taskType === 1030103) {
    //             row.mechanicalList.push(child)
    //           }
    //           if(child.taskType === 1030201 || child.taskType === 1030202 || child.taskType === 1030203) {
    //             row.electricalList.push(child)
    //           }
    //         }
    //       }
    //     }
    //   }
    // }
    pagination.total = res?.result.total;
    pagination.pageSize = res?.result.perPage*1;
    if(res?.result.perPage === 0) {
      pagination.pageSize = 1
    }
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.page = 1;
    form.projectName = null;
    form.projectNo = null;
    form.projectType = null;
    form.taskType = null;
    form.status = null;
    form.timeType = null;
    form.rangeDate = null;
    form.electControl = null;
    form.consignType = null;
    form.isDelive = null;
    form.receiptFull = null;
    formEl.resetFields();
    onSearch();
  };

  // 删除参数为空的键值
  function cleanEmptyData(obj: object) {
    Object.keys(obj).forEach(key => {
      if (obj[key] === null || obj[key] === '') {
        delete obj[key];
      }
    });
    return obj
  }
  const userSelect = ref()
  const elLoading = ref()
  async function openDialog(title = "创建项目", row?: FormItemProps) {
    let formInline: any = {
      title: title,
      userSelect: userSelect.value?.result,
      noticeType: ['station', 'dingtalk'],
      rangeDate: [],
      rangePlanDate: [],
      projectId: row?.projectId ?? null,
      projectName: null,
      projectNo: null,
      taskList: null,
      electControl: 0,
      consignType: 1,
      attachment: {
        contract: null,
        contractList: null,
        technicalProtocol: null,
      },
      detail: {}
    }
    let res = null
    if(title !== '创建项目') {
      res = await projectShowApi({ projectId: row.projectId });
    }
    if(title === '编辑项目') {
      formInline = {
        title: title,
        userSelect: userSelect.value?.result,
        projectId: res?.result?.projectId ?? "",
        projectName: res?.result?.projectName ?? "",
        projectNo: res?.result?.projectNo ?? "",
        projectType: res?.result?.projectType === 4 ? 3:res?.result?.projectType ?? "",
        projectFlagType: res?.result?.projectType ?? "",
        amount: res?.result?.amount*1 ?? "",
        advanceRatio: res?.result?.advanceRatio ?? "",
        startDate: res?.result?.startDate ?? "",
        endDate: res?.result?.endDate ?? "",
        planStartDate: res?.result?.planStartDate ?? "",
        planEndDate: res?.result?.planEndDate ?? "",
        effectDay: res?.result?.effectDay ?? "",
        principalUserId: res?.result?.principalUserId ?? "",
        description: res?.result?.description ?? "",
        budgetIsPend: res?.result?.budgetIsPend ?? "",
        attachment: res?.result?.attachment ?? "",
        consignRatio: res?.result?.consignRatio ?? "",
        checkRatio: res?.result?.checkRatio ?? "",
        qualityRatio: res?.result?.warrantyRatio ?? "",
        warrantyDuration: res?.result?.warrantyDuration ?? "",
        warrantyPayment: res?.result?.warrantyPayment ?? "",
        isPrivate: res?.result?.isPrivate ?? "",
        taskList: res?.result?.taskList ?? [],
        noticeType: res?.result?.noticeType  ?? null,
        electControl: res?.result?.electControl  ?? null,
        consignType: res?.result?.consignType  ?? null,
      };
      if(formInline.noticeType) {
        formInline.noticeType = JSON.parse(formInline.noticeType)
      } else {
        formInline.noticeType = []
      }
      formInline.rangeDate = [res?.result?.startDate, res?.result?.endDate]
      formInline.rangePlanDate = [res?.result?.planStartDate, res?.result?.planEndDate]
    }
    if(title === '任务详情') {
      formInline.taskList = row.taskList
    }
    if(title === '项目详情') {
      formInline.detail = res?.result
    }
    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      top: "2%",
      width: title === '任务详情'?'90%':"750px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: title === '任务详情' || title === '项目详情' ? true : false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if(title === '启动项目') {

            } else {
              // if(!curData.attachment?.contract) {
              //   message("请上传附件", {
              //     type: "error"
              //   });
              //   return
              // }
              let num = curData.qualityRatio + curData.advanceRatio + curData.consignRatio + curData.checkRatio;
              if(num>100) {
                message("金额比例已超过100%，请检查金额比例", {
                  type: "error"
                });
                return
              }
              if(num < 100) {
                message("金额比例不足100%，请检查金额比例", {
                  type: "error"
                });
                return
              }
              if(curData.noticeType.length === 0) {
                message("通知方式不能为空", {
                  type: "error"
                });
                return
              }
              const falg = curData.noticeType.includes('station')
              if(!falg) {
                message("通知方式中必须包含站内通知", {
                  type: "error"
                });
                return
              }
              let attachment = {
                contract: curData.attachment?.contract,
                contract_list: curData.attachment?.contractList,
                technical_protocol: curData.attachment?.technicalProtocol
              }
              if(!curData.attachment?.contract) {
                message("请上传合同", {
                  type: "error"
                });
                return
              }
              if(!curData.attachment?.contractList) {
                message("请上传清单", {
                  type: "error"
                });
                return
              }
              if(!curData.attachment?.technicalProtocol) {
                message("请上传技术协议", {
                  type: "error"
                });
                return
              }
              const params = {
                projectId: curData.projectId,
                projectName: curData.projectName,
                projectNo: curData.projectNo,
                projectType: curData.projectType === 3?curData.produceRadio?4:3:curData.projectType,
                amount: curData.amount.toFixed(2),
                advanceRatio: curData.advanceRatio,
                consignRatio: curData.consignRatio,
                checkRatio: curData.checkRatio,
                warrantyRatio: curData.qualityRatio,
                warrantyDuration: curData.warrantyDuration,
                warrantyPayment: curData.warrantyPayment,
                startDate: curData.rangeDate[0],
                endDate: curData.rangeDate[1],
                planStartDate: curData.rangePlanDate[0],
                planEndDate: curData.rangePlanDate[1],
                effectDay: curData.effectDay,
                principalUserId: curData.principalUserId,
                description: curData.description,
                budgetIsPend: curData.budgetIsPend,
                attachment: attachment,
                isPrivate: 1,
                // isPrivate: curData.isPrivate,
                createTask: curData.createTask,
                noticeType: curData.noticeType ?? [],
                electControl: curData.electControl,
                consignType: curData.consignType,
              }
              if (title === "创建项目") {
                projectStoreApi(params).then(async(res: any) => {
                  if(res?.code === 200) {
                    await done();
                    onSearch();
                    elLoading.value = ElLoading.service({
                      lock: true,
                      text: 'Loading',
                      background: 'rgba(0, 0, 0, 0.7)',
                    })
                    setTimeout(()=> {
                      multipleTaskChange(res.result.projectId)
                    }, 1000)

                  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
              } else {
                projectUpdateApi(params).then((res: any) => {
                  if(res?.code ===200) {
                    chores();
                  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
              }
            }

          }
        });
      }
    });
  }
  onMounted(async () => {
    await getProjectList();

    userSelect.value = await userSelectApi()
    onSearch(); //初始化数据
    getTypeSelect(); // 任务类型列表

  });
  // 类型列表
  const getTypeSelect = async() => {
    const res: any = await typeSelect();
    let children = []
    for (let item of res?.result) {
      if(item?.child) {
        for (let row of item?.child) {
          for (let child of row) {
            children.push(child)
          }
        }
        item.child= children
      }
    }
    form.taskTypeOptions = [...res?.result, ...children]

    form.taskTypeOptionsCopy = res?.result
  }

  function handleDelete(row) {
    ElMessageBox.confirm('确定继续进行删除操作?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      projectDeleteApi({ projectId: row.projectId }).then((res: any) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })

  }
  const treeIndex = ref(2)
  function treeChange(index: number) {
    if(index === 1) {
      form.listType = ""
    } else {
      form.listType = "tree"
    }
    pagination.total = 0;
    pagination.pageSize = 10;
    pagination.currentPage = 1;
    dataList.value = [];
    treeIndex.value = index
    onSearch();
  }

  function newDate(t, n) {
    // 创建一个新的日期对象，以防修改原始对象
    let resultDate = new Date(t);
    let currentDay = resultDate.getDay(); // 获取当前是星期几，0（周日）到6（周六）
    let daysToAdd = n;

    // 如果是周末，我们需要先跳过周末
    if (currentDay === 0) { // 周日
        daysToAdd--; // 需要额外的一天来开始工作日
        resultDate.setDate(resultDate.getDate() + 1); // 跳过周日
    } else if (currentDay === 6) { // 周六
        daysToAdd--; // 需要额外的一天来开始工作日
        resultDate.setDate(resultDate.getDate() + 2); // 跳过周六和周日
    }

    // 添加剩余的工作日天数
    while (daysToAdd > 0) {
        resultDate.setDate(resultDate.getDate() + 1); // 每天增加一天
        currentDay = resultDate.getDay(); // 更新当前星期几
        if (currentDay !== 0 && currentDay !== 6) { // 如果不是周末，减少剩余需要添加的工作日天数
            daysToAdd--;
        }
    }
    return `${resultDate.getFullYear()}-${('0' + (resultDate.getMonth() + 1)).slice(-2)}-${('0' + resultDate.getDate()).slice(-2)}`
  }
  // 计算工作日
  function calculateWorkingDays(startDate, endDate) {
    let currentDate = new Date(startDate);
    let end = new Date(endDate);
    let workDays = 0;

    while (currentDate <= end) {
      const day = currentDate.getDay();
      if (day !== 0 && day !== 6) { // 0 是周日，6 是周六
        workDays++;
      }
      currentDate.setDate(currentDate.getDate() + 1);
    }

    return workDays;
  }
  function getCalculatedDate(t) {
    const resultDate = new Date(t);
    resultDate.setDate(resultDate.getDate() - 1);
    return `${resultDate.getFullYear()}-${('0' + (resultDate.getMonth() + 1)).slice(-2)}-${('0' + resultDate.getDate()).slice(-2)}`
  }
  const multipleTaskFormRef = ref()
  async function multipleTaskChange(projectId: number) {
    let arrObj = []

    const res: any = await projectShowApi({ projectId: projectId });


    let dataList = res?.result.taskList;
    let planStartDate =  res?.result.planStartDate;

    for (let item of dataList) {
      let assignedTo = null
      if(item.taskTypeInit && item.taskTypeInit.assignedUsers) {
        assignedTo = JSON.parse(item.taskTypeInit.assignedUsers)
      }
      if(item.assigneds && item.assigneds.length > 0) {
        assignedTo = item.assigneds
      }
      let arrUser = []
      let assignedExtraTo = []
      if(assignedTo) {
        let assignedArr: any = Object.values(assignedTo)
        for (let row of assignedArr) {
          arrUser.push(row?.userId)
        }
      }

      if(item.assignedExtraTo && item.assignedExtraTo.length > 0) {
        for (let row of item.assignedExtraTo) {
          assignedExtraTo.push(row.userId)
        }
      }
      arrObj.push({
        taskType: item.taskType ?? item.taskTypeInit?.taskType,
        taskId: item.taskId ?? "",
        assignedTo: arrUser,
        rangePlanDate: item.planEndDate !== '--'?[item.planStartDate, item.planEndDate]:item.taskTypeInit?[planStartDate, newDate(planStartDate, item.taskTypeInit?.duration ?? 0)]:null,
        priority: item.priority ?? item.taskTypeInit?.priority ?? 1,
        duration: item.duration ?? item.taskTypeInit?.duration ?? "",
        // expectHour: item.expectHour ? item.expectHour : item.taskTypeInit && item.taskTypeInit.duration ? item.taskTypeInit.duration*8:"",
        expectHour: item.expectHour ? item.expectHour : item.taskTypeInit && item.taskTypeInit.duration ? "":"",
        description: item.description ?? item.taskTypeInit?.description ?? "",
        keyword: item.keyword ?? item.taskTypeInit?.keyword ?? "",
        assignedExtraTo: assignedExtraTo ?? null,
        completeRate: item.completeRate??0,
        disabledDate: null,
        isFlag: item.planEndDate !== '--' ? true : false,
        status: item.status,
        children: item.childrens,
        taskTypeName: item.taskTypeName,
        parentId: item.childrens.length > 0 ?item.childrens[0].parentId : 0
      })

    }


    // if(arrObj.length > 0) {
    //   for (let i = 1; i < arrObj.length; i++) {
    //     if(arrObj[i].rangePlanDate && !arrObj[i].isFlag && i !== 2) {
    //       arrObj[i].rangePlanDate = [dayjs(arrObj[i-1].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(arrObj[i-1].rangePlanDate[1], arrObj[i].duration)]
    //     }
    //   }
    // }
    if(arrObj[0].isFlag) {
      for (let item of arrObj) {
        if(item.children.length > 0){
          for (let row of item.children) {
            let arrUser = []
            let assignedExtraTo = []
            let assignedTo = null
            if(row.taskTypeInit && row.taskTypeInit.assignedUsers) {
              assignedTo = JSON.parse(row.taskTypeInit.assignedUsers)
            }
            if(row.assigneds && row.assigneds.length > 0) {
              assignedTo = row.assigneds
            }
            if(assignedTo) {
              let assignedArr: any = Object.values(assignedTo)
              for (let row of assignedArr) {
                arrUser.push(row?.userId)
              }
            }
            if(row.assignedExtraTo && row.assignedExtraTo.length > 0) {
              for (let child of row.assignedExtraTo) {
                assignedExtraTo.push(child.userId)
              }
            }
            row.assignedTo = arrUser
            row.rangePlanDate = row.planEndDate !== '--'?[row.planStartDate, row.planEndDate]:row.taskTypeInit?[planStartDate, newDate(planStartDate, row.taskTypeInit?.duration ?? 0)]:null;
            row.priority = row.priority ?? row.taskTypeInit?.priority ?? 1;
            row.duration = row.duration ?? row.taskTypeInit?.duration ?? "";
            row.expectHour = row.expectHour ? row.expectHour : row.taskTypeInit && row.taskTypeInit.duration ? row.taskTypeInit.duration*8:"";
            row.description = row.description ?? row.taskTypeInit?.description ?? "";
            row.keyword = row.keyword ?? row.taskTypeInit?.keyword ?? "";
            row.assignedExtraTo = assignedExtraTo ?? null;
            row.completeRate = row.completeRate ?? 0;
            row.disabledDate = null;
            row.isFlag = item.planEndDate !== '--' ? true : false

          }
        }
      }
    } else {
      if(!arrObj[1].isFlag) {
        arrObj[1].rangePlanDate = [dayjs(arrObj[0].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(arrObj[0].rangePlanDate[1], arrObj[1].duration)]
      }

      for (let item of arrObj) {
        if(item.children.length > 0){
          for (let row of item.children) {
            let arrUser = []
            let assignedExtraTo = []
            let assignedTo = null
            if(row.taskTypeInit && row.taskTypeInit.assignedUsers) {
              assignedTo = JSON.parse(row.taskTypeInit.assignedUsers)
            }
            if(row.assigneds && row.assigneds.length > 0) {
              assignedTo = row.assigneds
            }
            if(assignedTo) {
              let assignedArr: any = Object.values(assignedTo)
              for (let row of assignedArr) {
                arrUser.push(row?.userId)
              }
            }
            if(row.assignedExtraTo && row.assignedExtraTo.length > 0) {
              for (let child of row.assignedExtraTo) {
                assignedExtraTo.push(child.userId)
              }
            }
            row.assignedTo = arrUser
            // row.rangePlanDate = row.planEndDate !== '--'?[row.planStartDate, row.planEndDate]:row.taskTypeInit?[planStartDate, newDate(planStartDate, row.taskTypeInit?.duration ?? 0)]:null;
            row.priority = row.priority ?? row.taskTypeInit?.priority ?? 1;
            // row.duration = row.duration ?? row.taskTypeInit?.duration ?? "";
            // row.expectHour = row.expectHour ? row.expectHour : row.taskTypeInit && row.taskTypeInit.duration ? row.taskTypeInit.duration*8:"";
            // row.description = row.description ?? row.taskTypeInit?.description ?? "";
            // row.keyword = row.keyword ?? row.taskTypeInit?.keyword ?? "";
            // row.assignedExtraTo = assignedExtraTo ?? null;
            // row.completeRate = row.completeRate ?? 0;
            // row.disabledDate = null;
            // row.isFlag = item.planEndDate !== '--' ? true : false

          }
          let arr = []
          for (let row of item.children) {
            for (let child of row?.assignedTo) {
              arr.push(child)
            }
          }
          item.assignedTo = [...new Set(arr)]
          // if(item.children.length > 0) {
          //   if(item.children[0].rangePlanDate && item.children[0].isFlag) {
          //     item.children[0].rangePlanDate = [dayjs(arrObj[1].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(dayjs(arrObj[1].rangePlanDate[1]).format('YYYY-MM-DD'), item.children[0].duration)]
          //   }

          //   for (let i = 1; i < 3; i++) {
          //     if(item.children[i].rangePlanDate && item.children[i].isFlag) {
          //       item.children[i].rangePlanDate = [dayjs(item.children[i-1].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(item.children[i-1].rangePlanDate[1], item.children[i].duration)]
          //     }
          //   }
          //   if(item.children.length >3) {
          //     if(item.children[3].rangePlanDate && item.children[3].isFlag) {
          //       item.children[3].rangePlanDate = [dayjs(arrObj[1].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(dayjs(arrObj[1].rangePlanDate[1]).format('YYYY-MM-DD'), item.children[0].duration)]
          //       for (let i = 4; i < 6; i++) {
          //         if(item.children[i].rangePlanDate && item.children[i].isFlag) {
          //           item.children[i].rangePlanDate = [dayjs(item.children[i-1].rangePlanDate[1]).format('YYYY-MM-DD'), newDate(item.children[i-1].rangePlanDate[1], item.children[i].duration)]
          //         }
          //       }
          //     }

          //   }
          //   for (let i = 0; i < item.children.length; i++) {
          //     if(item.children[i].rangePlanDate && item.children[i].isFlag) {
          //       item.children[i].rangePlanDate = [dayjs(item.children[i].rangePlanDate[0]).format('YYYY-MM-DD') + ' 08:30:00', dayjs(getCalculatedDate(item.children[i].rangePlanDate[1])).format('YYYY-MM-DD')+' 18:00:00']
          //     }

          //   }
          //   if(item.children.length === 3) {
          //     item.rangePlanDate = [item.children[0].rangePlanDate[0], item.children[2].rangePlanDate[1]]
          //   } else if(item.children.length === 6) {
          //       let date1 = dayjs(item.children[0].rangePlanDate[0]);
          //       let date2 = dayjs(item.children[3].rangePlanDate[0]);
          //       let end1 = dayjs(item.children[2].rangePlanDate[1]);
          //       let end2 = dayjs(item.children[5].rangePlanDate[1]);
          //       item.rangePlanDate = [date1.isBefore(date2)?item.children[3].rangePlanDate[0]:item.children[0].rangePlanDate[0],
          //       end1.isBefore(end2)?item.children[2].rangePlanDate[1]:item.children[5].rangePlanDate[1]]

          //   }


          // }

        }

      }
      // if(arrObj.length > 0) {
      //   for (let i = 3; i < arrObj.length; i++) {
      //     if(i === 3) {
      //       arrObj[3].rangePlanDate = [dayjs(arrObj[2].rangePlanDate[1]).add(1, 'day').format('YYYY-MM-DD'), newDate(dayjs(arrObj[2].rangePlanDate[1]).add(1, 'day').format('YYYY-MM-DD'), arrObj[i].duration)]
      //     }
      //     let p = arrObj[i-1].rangePlanDate?arrObj[i-1].rangePlanDate[1]:''
      //     if(arrObj[i].rangePlanDate && !arrObj[i].isFlag && i !== 3) {
      //       arrObj[i].rangePlanDate = [dayjs(p).format('YYYY-MM-DD'), newDate(p, arrObj[i].duration)]
      //     }
      //   }
      // }

      // if(arrObj.length > 0) {
      //   for (let i = 0; i < arrObj.length; i++) {
      //     if(arrObj[i].children && arrObj[i].children.length > 0) {
      //       arrObj[i].expectHour = calculateWorkingDays(arrObj[i].rangePlanDate[0], arrObj[i].rangePlanDate[1]) * 8
      //     }
      //     if(arrObj[i].rangePlanDate && i !== 2) {
      //       arrObj[i].rangePlanDate = [dayjs(arrObj[i].rangePlanDate[0]).format('YYYY-MM-DD') + ' 08:30:00', dayjs(getCalculatedDate(arrObj[i].rangePlanDate[1])).format('YYYY-MM-DD')+' 18:00:00']
      //     }

      //   }
      // }
    }

    elLoading.value?.close()
    addDialog({
      title: '批量任务',
      titleSlot: `<span class="ml-[20px]">
      <span>【项目名称：${res?.result.projectName}</span>
      <span class="ml-[30px]">项目编码：${res?.result.projectNo}</span>
      <span class="ml-[30px]">计划日期：${res?.result.planStartDate} 至 ${res?.result.planEndDate}】</span>
    </span>`,
      props: {
        formInline: {
          projectInfo: res?.result,
          userSelect: userSelect.value.result,
          tableList: arrObj,
          taskTypeSelect: form.taskTypeOptions,
          status: res?.result.status,
          fn: onSearch
        }
      },
      top: '4%',
      width: "90%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: true,
      contentRenderer: () => h(multipleTaskForm, { ref: multipleTaskFormRef }),
      beforeSure: (done, { options }) => {
        const FormRef = multipleTaskFormRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;


        function chores() {
          message(`操作成功`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let params = {
              projectId: curData.projectSelect.projectId,
              taskList: []
            }
            for (let item of curData.tableList) {
              if(!item.taskType) {
                message("请选择任务类型", {
                  type: "error"
                });
                return
              }
              if(!item.assignedTo) {
                message("请选择指派用户", {
                  type: "error"
                });
                return
              }
              if(!item.rangePlanDate) {
                message("请选择计划日期", {
                  type: "error"
                });
                return
              }
              if(!item.priority) {
                message("请输入优先级", {
                  type: "error"
                });
                return
              }
              if(!item.expectHour) {
                message("请输入预计小时", {
                  type: "error"
                });
                return
              }
            }
            let child = []
            for (let item of curData.tableList) {
              if(item.children && item.children.length > 0) {
                for (let row of item.children) {
                  child.push({
                    taskId: row.taskId,
                    taskType: row.taskType,
                    parentId: row.parentId,
                    hasMultiUser: row.assignedTo.length >1?1:0,
                    assignedTo: row.assignedTo,
                    planStartDate: (row.rangePlanDate[0].match(/:/g) || []).length ===1?row.rangePlanDate[0]+':00':row.rangePlanDate[0],
                    planEndDate: (row.rangePlanDate[1].match(/:/g) || []).length ===1?row.rangePlanDate[1]+':00':row.rangePlanDate[1],
                    priority: row.priority,
                    expectHour: row.expectHour,
                    description: row.description,
                    keyword: row.keyword,
                    assignedExtraTo: row.assignedExtraTo ?? [],
                    completeRate: row.completeRate,
                  })
                }
              }


              params.taskList.push({
                taskId: item.taskId,
                taskType: item.taskType,
                parentId: 0,
                hasMultiUser: item.assignedTo.length >1?1:0,
                assignedTo: item.assignedTo,
                planStartDate: (item.rangePlanDate[0].match(/:/g) || []).length ===1?item.rangePlanDate[0]+':00':item.rangePlanDate[0],
                planEndDate: (item.rangePlanDate[1].match(/:/g) || []).length ===1?item.rangePlanDate[1]+':00':item.rangePlanDate[1],
                priority: item.priority,
                expectHour: item.expectHour,
                description: item.description,
                keyword: item.keyword,
                // attachment: [baseOaApi + item.fileList[0].response.result.path],
                assignedExtraTo: item.assignedExtraTo ?? [],
                completeRate: item.completeRate,
              })
            }
            params.taskList = [...params.taskList, ...child]
            params.taskList.sort((a, b) => a.taskType - b.taskType)

            taskBulkStoreApi(cleanEmptyData(params)).then((res: any) => {
              if(res?.code ===200) {
                chores();
              }
            })
            .catch(error => {
              message(error.response.data.msg ?? "操作失败,请联系管理员", {
                type: "error"
              });
            });
          }
        });
      }
    })
  }
  const taskFormRef = ref()
  async function taskDialog(row) {
    const res: any = await taskShowApi({ taskId: row.taskId });
    if(res?.code !==200) {
      return
    }
    console.log(row)
    let assignedTo = []
    let assignedExtraTo = []
    for (let item of res.result.assigneds) {
      assignedTo.push(item.userId)
    }
    for (let item of res.result.assignedExtras) {
      assignedExtraTo.push(item.userId)
    }
    addDialog({
      title: '编辑任务',
      props: {
        formInline: {
          projectId: row.projectId,
          taskId: row.taskId,
          taskType: row.taskType,
          taskTypeName: row.taskTypeName,
          projectSelect: projectSelect.value,
          userSelect: userSelect.value.result,
          rangePlanDate: [row.planStartDate, row.planEndDate],
          priority: row.priority || 1,
          hasMultiUser: row.hasMultiUser,
          description: row.description,
          keyword: row.keyword,
          completeRate: row.completeRate,
          expectHour: row.expectHour,
          assignedTo: assignedTo,
          assignedExtraTo: assignedExtraTo,
          attachment: []
        }
      },
      width: "650px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(taskForm, { ref: taskFormRef }),
      beforeSure: (done, { options }) => {
        const FormRef = taskFormRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        console.log(curData, FormRef)


        function chores() {
          message(`操作成功!`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            let attachment = []
            for (let item of curData.attachment) {
              if(item) {
                attachment.push( baseOaApi + item.response.result.path)
              }
            }
            let params = {
              projectId: curData.projectId,
              taskId: curData.taskId,
              hasMultiUser: curData.hasMultiUser,
              assignedTo: curData.assignedTo,
              planStartDate: (curData.rangePlanDate[0].match(/:/g) || []).length ===1?curData.rangePlanDate[0]+':00':curData.rangePlanDate[0],
              planEndDate:  (curData.rangePlanDate[1].match(/:/g) || []).length ===1?curData.rangePlanDate[1]+':00':curData.rangePlanDate[1],
              priority: curData.priority,
              expectHour: curData.expectHour,
              description: curData.description,
              keyword: curData.keyword,
              attachment: attachment,
              assignedExtraTo: curData.assignedExtraTo,
              completeRate: curData.completeRate,
              taskType: curData.taskType,
            }
            taskUpdateApi(cleanEmptyData(params)).then((res: any) => {
              if(res?.code ===200) {
                chores();
              }
            })
            .catch(error => {
              message(error.response.data.msg ?? "操作失败,请联系管理员", {
                type: "error"
              });
            });
          }
        });
      }
    })
  }
  const projectSelect = ref()
  async function getProjectList() {
    const res: any = await projectSelectApi({type: 'all'});
    projectSelect.value = res?.result;
  }
  function invoicingDetail (row) {
    addDialog({
      top: "5vh",
      width: "600px",
      title: "开票详情",
      hideFooter: true,
      contentRenderer: () => h(InvDetails),
      props: {
        info: row.invoice
      }
    });
  }

  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    treeChange,
    treeIndex,
    multipleTaskChange,
    userSelect,
    taskDialog,
    invoicingDetail,
    expandColumns
  };
}
